package com.cuitrip.util.text;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;

/**
 * Created by MiJack on 2015/11/29.
 */
public abstract class BaseTextWatcher implements TextWatcher {
    protected boolean isFormatting;
    protected boolean deletingHyphen;
    protected int hyphenStart;
    protected boolean deletingBackward;

    @Override
    public void afterTextChanged(Editable text) {
        if (isFormatting)
            return;

        isFormatting = true;

        // If deleting hyphen, also delete character before or after it
        if (deletingHyphen && hyphenStart > 0) {
            if (deletingBackward) {
                if (hyphenStart - 1 < text.length()) {
                    deleteText(text, hyphenStart - 1, hyphenStart);
//                    text.delete(hyphenStart - 1, hyphenStart);
                }
            } else if (hyphenStart < text.length()) {
                deleteText(text, hyphenStart, hyphenStart + 1);
//                text.delete(hyphenStart, hyphenStart + 1);
            }
        }
        format(text);

        isFormatting = false;
    }

    protected void deleteText(Editable text, int start, int end) {
        text.delete(start, end);
    }

    public abstract void format(Editable text);

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (isFormatting)
            return;

        // Make sure user is deleting one char, without a selection
        final int selStart = Selection.getSelectionStart(s);
        final int selEnd = Selection.getSelectionEnd(s);
        if (s.length() > 1 // Can delete another character
                && count == 1 // Deleting only one character
                && after == 0 // Deleting
                && s.charAt(start) == ' ' // a hyphen
                && selStart == selEnd) { // no selection
            deletingHyphen = true;
            hyphenStart = start;
            // Check if the user is deleting forward or backward
            if (selStart == start + 1) {
                deletingBackward = true;
            } else {
                deletingBackward = false;
            }
        } else {
            deletingHyphen = false;
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
}
